<template>
  <div class="login-page">
    <div class="login-container">
      <!-- 左侧品牌展示区域 -->
      <div class="brand-section">
        <div class="brand-content">
          <div class="brand-logo">
            <el-icon :size="60" color="#409eff">
              <House />
            </el-icon>
          </div>
          <h1 class="brand-title">洗护专家</h1>
          <p class="brand-subtitle">专业的洗护服务平台</p>
          <div class="brand-features">
            <div class="feature-item">
              <el-icon><CircleCheck /></el-icon>
              <span>专业技师</span>
            </div>
            <div class="feature-item">
              <el-icon><Clock /></el-icon>
              <span>快速响应</span>
            </div>
            <div class="feature-item">
              <el-icon><Star /></el-icon>
              <span>优质服务</span>
            </div>
            <div class="feature-item">
              <el-icon><Check /></el-icon>
              <span>安全保障</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧登录表单 -->
      <div class="form-section">
        <div class="form-card">
          <div class="form-header">
<<<<<<< HEAD
            <h2>用户登录</h2>
            <p>请输入您的账号信息</p>
=======
            <h2>欢迎回来</h2>
            <p>登录您的账户以继续使用服务</p>
            <!-- 返回首页按钮 -->
            <el-button 
              type="text" 
              @click="goToHome" 
              class="back-home-btn"
              style="margin-top: 10px; color: #409eff;"
            >
              <el-icon><ArrowLeft /></el-icon>
              返回首页
            </el-button>
>>>>>>> c61637f (所有前后端正常登录)
          </div>

          <!-- 登录方式切换 -->
          <div class="login-tabs">
            <div 
              class="tab-item"
              :class="{ active: loginType === 'password' }"
              @click="loginType = 'password'"
            >
              密码登录
            </div>
            <div 
              class="tab-item"
              :class="{ active: loginType === 'code' }"
              @click="loginType = 'code'"
            >
              验证码登录
            </div>
          </div>

          <!-- 密码登录表单 -->
          <el-form 
            v-if="loginType === 'password'"
            :model="passwordForm" 
            :rules="passwordRules" 
            ref="passwordFormRef"
            class="login-form"
          >
            <el-form-item prop="username">
              <el-input
                v-model="passwordForm.username"
                placeholder="请输入手机号/用户名"
                size="large"
                clearable
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="passwordForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                show-password
                clearable
                @keyup.enter="handlePasswordLogin"
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <div class="form-options">
              <el-checkbox v-model="passwordForm.rememberMe">
                记住密码
              </el-checkbox>
              <a href="#" @click.prevent="goToForgotPassword" class="forgot-link">
                忘记密码？
              </a>
            </div>

            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="loading"
                @click="handlePasswordLogin"
                class="login-btn"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 验证码登录表单 -->
          <el-form 
            v-else
            :model="codeForm" 
            :rules="codeRules" 
            ref="codeFormRef"
            class="login-form"
          >
            <el-form-item prop="mobile">
              <el-input
                v-model="codeForm.mobile"
                placeholder="请输入手机号"
                size="large"
                clearable
                maxlength="11"
                @input="handleMobileInput"
              >
                <template #prefix>
                  <el-icon><Phone /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="code">
              <div class="code-input">
                <el-input
                  v-model="codeForm.code"
                  placeholder="请输入6位验证码"
                  size="large"
                  clearable
                  maxlength="6"
                  @keyup.enter="handleCodeLogin"
                >
                  <template #prefix>
                    <el-icon><Message /></el-icon>
                  </template>
                </el-input>
                <el-button 
                  @click="sendCode" 
                  :disabled="countdown > 0 || !codeForm.mobile || !/^1[3-9]\d{9}$/.test(codeForm.mobile)"
                  class="code-btn"
                  size="large"
                  :loading="sendingCode"
                >
                  {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="loading"
                @click="handleCodeLogin"
                class="login-btn"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 注册链接 -->
          <div class="form-footer">
            <div class="register-prompt">
              <span>还没有账号？</span>
              <a href="#" @click.prevent="goToRegister" class="register-link">立即注册</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import {
  House,
  CircleCheck,
  Clock,
  Star,
  Check,
  User,
  Lock,
  Phone,
<<<<<<< HEAD
  Message
=======
  Message,
  ArrowLeft
>>>>>>> c61637f (所有前后端正常登录)
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)
const loginType = ref('password')
const passwordFormRef = ref()
const codeFormRef = ref()

// 密码登录表单
const passwordForm = reactive({
  username: '',
  password: '',
  rememberMe: false
})

// 验证码登录表单
const codeForm = reactive({
  mobile: '',
  code: ''
})

// 表单验证规则
const passwordRules = {
  username: [
    { required: true, message: '请输入手机号或用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' }
  ]
}

const codeRules = {
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

// 初始化记住的用户名
onMounted(() => {
  console.log('登录页面初始化')
  const rememberedUsername = localStorage.getItem('rememberedUsername')
  if (rememberedUsername) {
    passwordForm.username = rememberedUsername
    passwordForm.rememberMe = true
    console.log('已恢复记住的用户名:', rememberedUsername)
  }
})

// 处理手机号输入
const handleMobileInput = (value) => {
  // 只保留数字
  const cleanValue = value.replace(/\D/g, '')
  // 限制11位
  codeForm.mobile = cleanValue.slice(0, 11)
  console.log('手机号输入:', codeForm.mobile)
}

// 发送验证码
const sendCode = async () => {
  if (!/^1[3-9]\d{9}$/.test(codeForm.mobile)) {
    ElMessage.error('请输入正确的手机号')
    return
  }

  try {
    sendingCode.value = true
    await userStore.sendSmsCode(codeForm.mobile)
    ElMessage.success('验证码已发送到您的手机')
    
    // 开始60秒倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    
  } catch (error) {
    console.error('发送验证码失败:', error)
    if (error.response?.status === 403) {
      ElMessage.error('权限不足，无法发送验证码')
    } else if (error.response?.status === 429) {
      ElMessage.error('发送过于频繁，请稍后再试')
    } else {
      ElMessage.error('发送验证码失败，请重试')
    }
  } finally {
    sendingCode.value = false
  }
}

// 密码登录
const handlePasswordLogin = async () => {
  try {
    await passwordFormRef.value.validate()
    loading.value = true
    console.log('尝试密码登录:', passwordForm.username)
    
    await userStore.login({
      username: passwordForm.username,
      password: passwordForm.password
    })
    
    ElMessage.success('登录成功！欢迎回来')
    console.log('登录成功')
    
    // 记住密码处理
    if (passwordForm.rememberMe) {
      localStorage.setItem('rememberedUsername', passwordForm.username)
    } else {
      localStorage.removeItem('rememberedUsername')
    }
    
    redirectAfterLogin()
    
  } catch (error) {
    if (error.errors) return // 表单验证错误
    console.error('登录失败:', error)
    
    if (error.response?.status === 401) {
      ElMessage.error('用户名或密码错误')
    } else if (error.response?.status === 403) {
      ElMessage.error('账户已被禁用，请联系管理员')
    } else if (error.response?.status === 429) {
      ElMessage.error('登录尝试过于频繁，请稍后再试')
    } else {
      ElMessage.error('登录失败，请检查网络连接')
    }
  } finally {
    loading.value = false
  }
}

// 验证码登录
const handleCodeLogin = async () => {
  try {
    await codeFormRef.value.validate()
    loading.value = true
    console.log('尝试验证码登录:', codeForm.mobile, codeForm.code)
    
    await userStore.loginWithCode({
      mobile: codeForm.mobile,
      code: codeForm.code
    })
    
    ElMessage.success('登录成功！')
    console.log('验证码登录成功')
    redirectAfterLogin()
    
  } catch (error) {
    if (error.errors) return // 表单验证错误
    console.error('验证码登录失败:', error)
    
    if (error.response?.status === 401) {
      ElMessage.error('验证码错误或已过期')
    } else if (error.response?.status === 403) {
      ElMessage.error('账户已被禁用，请联系管理员')
    } else if (error.response?.status === 429) {
      ElMessage.error('登录尝试过于频繁，请稍后再试')
    } else {
      ElMessage.error('验证码登录失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 登录后重定向
const redirectAfterLogin = async () => {
<<<<<<< HEAD
  const redirect = route.query.redirect || '/home'
=======
  const redirect = route.query.redirect || '/user-home'
>>>>>>> c61637f (所有前后端正常登录)
  console.log('=== 登录后重定向调试 ===')
  console.log('登录成功，准备重定向到:', redirect)
  console.log('用户认证状态:', userStore.isAuthenticated)
  console.log('用户信息:', userStore.user)
  console.log('token:', !!userStore.token)
  console.log('isLoggedIn:', userStore.isLoggedIn)

<<<<<<< HEAD
  // 等待一个tick确保状态更新完成
  await nextTick()

  console.log('状态更新后 - 用户认证状态:', userStore.isAuthenticated)
  console.log('状态更新后 - isLoggedIn:', userStore.isLoggedIn)
=======
  // 等待状态更新，给更多时间确保状态同步
  await nextTick()
  await new Promise(resolve => setTimeout(resolve, 200))

  console.log('状态更新后 - 用户认证状态:', userStore.isAuthenticated)
  console.log('状态更新后 - isLoggedIn:', userStore.isLoggedIn)
  console.log('状态更新后 - token:', !!userStore.token)
>>>>>>> c61637f (所有前后端正常登录)

  // 确保重定向路径是安全的
  if (redirect.startsWith('/') && !redirect.startsWith('//')) {
    console.log('✅ 重定向路径安全，跳转到:', redirect)
<<<<<<< HEAD
    router.push(redirect)
  } else {
    console.log('⚠️ 重定向路径不安全，跳转到默认首页')
    router.push('/home')
=======
    await router.push(redirect)
  } else {
    console.log('⚠️ 重定向路径不安全，跳转到用户首页')
    await router.push('/user-home')
>>>>>>> c61637f (所有前后端正常登录)
  }

  // 清除URL中的redirect参数
  if (route.query.redirect) {
    router.replace({
      path: route.path,
      query: {}
    })
  }
}

// 跳转到忘记密码页面
const goToForgotPassword = () => {
  console.log('跳转到忘记密码页面')
  router.push('/forgot-password')
}

// 跳转到注册页面
const goToRegister = async () => {
  try {
    await router.push('/register')
  } catch (error) {
    console.error('跳转到注册页面失败:', error)
    ElMessage.error('页面跳转失败，请重试')
  }
}
<<<<<<< HEAD
=======

// 跳转到首页
const goToHome = () => {
  console.log('跳转到首页')
  router.push('/')
}
>>>>>>> c61637f (所有前后端正常登录)
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  max-width: 1000px;
  width: 100%;
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  min-height: 600px;
}

.brand-section {
  background: linear-gradient(135deg, #409eff 0%, #536dfe 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px 40px;
  position: relative;
  overflow: hidden;
}

.brand-section::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 1000'%3E%3Cg fill-opacity='0.03'%3E%3Cpolygon fill='%23fff' points='50 0 60 40 100 50 60 60 50 100 40 60 0 50 40 40'/%3E%3C/g%3E%3C/svg%3E") repeat;
  animation: float 20s infinite linear;
}

@keyframes float {
  0% { transform: translateY(0); }
  100% { transform: translateY(-100px); }
}

.brand-content {
  text-align: center;
  position: relative;
  z-index: 2;
}

.brand-logo {
  margin-bottom: 30px;
}

.brand-title {
  font-size: 2.5rem;
  font-weight: bold;
  margin: 0 0 15px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.brand-subtitle {
  font-size: 1.1rem;
  margin-bottom: 40px;
  opacity: 0.9;
}

.brand-features {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 0.9rem;
}

.form-section {
  padding: 60px 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  font-size: 2rem;
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.form-header p {
  color: #7f8c8d;
  margin: 0;
}

.login-tabs {
  display: flex;
  margin-bottom: 30px;
  border-radius: 8px;
  background: #f5f7fa;
  padding: 4px;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.3s ease;
  font-weight: 500;
}

.tab-item.active {
  background: #409eff;
  color: white;
}

.login-form {
  margin-bottom: 20px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.forgot-link {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
}

.forgot-link:hover {
  text-decoration: underline;
}

.code-input {
  display: flex;
  gap: 10px;
}

.code-input .el-input {
  flex: 1;
}

.code-btn {
  white-space: nowrap;
  min-width: 110px;
}

.login-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  border-radius: 8px;
}

.form-footer {
  text-align: center;
  margin-top: 20px;
}

.register-prompt {
  font-size: 14px;
  color: #606266;
}

.register-link {
  color: #409eff;
  text-decoration: none;
  margin-left: 5px;
}

.register-link:hover {
  text-decoration: underline;
}

<<<<<<< HEAD
=======
.back-home-btn {
  margin-top: 10px;
  color: #409eff;
}

>>>>>>> c61637f (所有前后端正常登录)
@media (max-width: 768px) {
  .login-container {
    grid-template-columns: 1fr;
    max-width: 400px;
  }

  .brand-section {
    display: none;
  }

  .form-section {
    padding: 40px 30px;
  }

  .form-header h2 {
    font-size: 1.5rem;
  }

  .brand-features {
    grid-template-columns: 1fr;
  }

  .code-input {
    flex-direction: column;
  }

  .code-btn {
    min-width: auto;
  }
}

@media (max-width: 480px) {
  .login-page {
    padding: 10px;
  }

  .form-section {
    padding: 30px 20px;
  }
}
</style> 